package com.test.demo;

import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Build;

import java.util.ArrayList;

public class PermissionUtils {

    public static final int REQUEST_CODE_PERMISSION = 10001;

    public static boolean verifyPermissions(Activity activity, String[] permNames) {
        boolean bCheck = true;
        try {
            ArrayList<String> newPerms = new ArrayList<>();
            for (String permName : permNames) {
                int permission = activity.getPackageManager().checkPermission(permName, activity.getPackageName());
                bCheck = (permission == PackageManager.PERMISSION_GRANTED);
                if (!bCheck ) {//6.0
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        permission = activity.checkSelfPermission(permName);
                        bCheck = (permission == PackageManager.PERMISSION_GRANTED);
                      }
                    if (!bCheck)
                        newPerms.add(permName);
                }
            }
            if (newPerms.size() > 0) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    String[] PERMISSIONS = new String[newPerms.size()];
                    newPerms.toArray(PERMISSIONS);
                    activity.requestPermissions(PERMISSIONS, REQUEST_CODE_PERMISSION);//如果有兼容库
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            bCheck = false;
        }
        return bCheck;
    }

}

